package com.afishing.servlet;

import com.afishing.dao.CartDao;
import com.afishing.dao.impl.CartDapImpl;
import com.afishing.entity.Shop;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "UpdateCartServlet", value = "/updateCart")
public class UpdateCartServlet extends HttpServlet {
    private final CartDao cartDao = new CartDapImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        // 从请求中获取购物车数据
        String cartJson = request.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);

        // 解析json字符串
        ArrayList<Shop> cartItems = (ArrayList<Shop>) JSONObject.parseArray(cartJson, Shop.class);

        // 更新数据库中的购物车数据
        cartDao.updateCart(cartItems);

        // 返回响应给客户端
        response.getWriter().write("{\"status\":\"success\"}");
    }
}